<template>
  <div>
     <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <home-main-template>
      <div slot="top">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input
              placeholder="请输入内容"
              class="input-with-select"
              v-model="queryInfo.query"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </div>
      <div slot="center">
        <el-table :data="userList" border stripe>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态" prop="mg_state">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChanged(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="role_name">
            <template slot-scope="scope">
              <el-button
                @click="showEditDialog(scope.row.id)"
                v-model="scope.row.role_name"
                type="primary"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
              <el-button
              @click="removeUserById(scope.row.id)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
              <el-button
                @click="setRole(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="bottom">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenumq"
          :page-sizes="[1, 2, 3, 4]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </home-main-template>
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close='addDialogClosed'>
      <el-form
        :model="addFrom"
        :rules="addFromRules"
        ref="addFromRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改用户" :visible.sync="showEdit" width="50%"  @close='editDialogClosed'>
      <el-form
        :model="editForm"
        :rules="editFromRules"
        ref="editFromRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="username">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="username">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEdit = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
     <el-dialog title="分配角色"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      @close="setRolesDialogClose"
    >
      <div>
        <p>当前的用户：{{ usersInfo.username }}</p>
        <p>当前的角色：{{ usersInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
              <!-- vmodel绑定的是value的值 -->
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import HomeMainTemplate from "../../../../components/content/HomeMainTemplate.vue";
import { getUserList, setUsersStatus, addUser,editUser,submit,removeUser,getRoleList,setNewRole} from "@/network/users";
export default {
  components: { HomeMainTemplate },
  name: "users",
  data() {
    return {
      userList: [],
      total: 0,
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前页数显示几个数据
        pagesize: 2,
      },
      //控制对话框显示与隐藏
      dialogVisible: false,
      showEdit:false,
      //添加用户表单数据
      addFrom:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      //添加表单验证规则对象
      addFromRules:{
        username:[
          {required: true, message: '请输入用户名称', trigger: 'blur'},
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password:[
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email:[
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        mobile:[
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 7, max: 11,message: '请输入正确的手机号码',}
        ]
      },
      //查询用户信息对象
      editForm:{},
      //修改用户信息验证规则对象
      editFromRules:{
        email:[
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        mobile:[
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 7, max: 11,message: '请输入正确的手机号码',}
        ]
      },
      // 需要分配权限的角色
      usersInfo: {},
      // 所有角色的列表
      rolesList: {},
      // 选中的角色
      selectedRolesId: ''
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      getUserList(
        this.queryInfo.query,
        this.queryInfo.pagenum,
        this.queryInfo.pagesize
      ).then((res) => {
        const { data, meta } = res;
        if (meta.status !== 200) return this.$message.error(meta.msg);
        this.userList = data.users;
        this.total = data.total;
      });
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pagenum = newSize;
      this.getUserList();
    },
    //监听switch开关改变
    userStateChanged(userInfo) {
      console.log(userInfo);
      setUsersStatus(userInfo.id, userInfo.mg_state).then((res) => {
        console.log(res);
        const { meta } = res;
        if (meta.status !== 200) return this.$message.error(meta.msg);
        return this.$message.success(meta.msg);
      });
    },
    addDialogVisible() {
      this.dialogVisible = true;
    },
    //监听添加对话框关闭事件
    addDialogClosed(){
       this.$refs.addFromRef.resetFields()
    },
    //点击按钮添加用户
    addUser(){
    this.$refs.addFromRef.validate((valid =>{
      if(!valid) return
      //发送请求
       addUser(this.addFrom.username,this.addFrom.password,this.addFrom.email,this.addFrom.mobile).then(
       res =>{
         const {meta} = res
         if(meta.status !== 201) {
           this.$message.error('添加失败')
         }
         this.$message.success('添加成功')
         this.dialogVisible = false
         this.getUserList()
       }
     )
    }))
   },
   //编辑用户对话框
   showEditDialog(id){
     this.showEdit = true
     editUser(id).then(
       res =>{
         const {data,meta} = res
         if (meta.status !== 200) return this.$message.error(meta.msg);
         this.editForm = data
       }
     )
    
   },
   //监听修改对话框关闭事件
   editDialogClosed(){
     this.$refs.editFromRef.resetFields()
   },
   //点击按钮修改用户
   editUserInfo(){
     this.$refs.editFromRef.validate((valid => {
        if(!valid) return
        console.log(valid)
        //发送请求
        submit(this.editForm.id, this.editForm.email,this.editForm.mobile).then(
           res =>{
             const meta = res
             if (meta.status !== 200) return this.$message.error(meta.msg);
           }
         )
     }))
     this.showEdit = false
     this.getUserList()
     this.$message.success('修改成功')
   },
   //删除用户操作
   removeUserById(id){
     //弹框询问
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(()=>{
          this.$message({
            type:'info',
            message:'已取消删除'
          })
        })
      removeUser(id).then(
        res =>{
          const {meta} = res
          if(meta.status !== 200) return this.$message.error(meta.msg);
          this.getUserList()
          console.log(res)
        }
      )
   },
    //展示分配角色的对话框
   setRoles(Info){
     this.usersInfo = Info
     getRoleList().then(
       res =>{
         const { data, meta } = res
         if (meta.status !== 200) return this.$message.error(meta.msg)
         this.rolesList = data
       }
     )
     this.setRolesDialogVisible = true
   },
   //确定后分配角色
   setRolesInfo(){
     if (!this.selectedRolesId) return this.$message.error('请分配角色')
     setNewRole(this.usersInfo.id, this.selectedRolesId).then(
       res =>{
         const {meta } = res
         if (meta.status !== 200) return this.$message.error(meta.msg)
         this.$msg.success(meta.msg)
         this.setRolesDialogVisible = false
         this.getUserList()
       }
     )
   },
   //监听分配角色对话框关闭后
    setRolesDialogClose() {
      this.selectedRolesId = ''
      this.usersInfo = {}
    }
 }
}
</script>

<style scoped>
.el-table {
  margin-top: 15px;
}
.el-dialog {
  position: fixed;
  z-index: 999;
}
.el-breadcrumb {
  margin-bottom: 15px;
}
</style>